package com.contract.Thread;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Observable;

import com.alibaba.fastjson.JSONObject;
import com.contract.dao.ContractDao;
import com.contract.dao.impl.ContractDaoImpl;
import com.contract.service.impl.ContractServiceImpl;
import com.contract.utils.CommTools;
import com.contract.utils.DateUtil;
import com.contract.utils.DemoSelenium;
import com.contract.utils.HttpUnitl;

public class ThreadContract extends Observable implements Runnable{

	private String name;
	
	private long times;
	
	// 此方法一经调用，立马可以通知观察者，在本例中是监听线程
    public void doBusiness() {
        if (true) {
            super.setChanged();
        }
        notifyObservers();
    }
	
	private ContractServiceImpl contractService = new ContractServiceImpl();
	
	
	public ThreadContract(String name,long times){
		this.name = name;
		this.times = times;
	}	
	@Override
	public void run() {	
		for(;;){
			 try { 
				System.err.println("开始接口");
				String week = DateUtil.getWeekOfDate(new Date());
				System.err.println(week);
				
				String day = CommTools.getDay();
				String nextday = CommTools.getNextDay(1);
				String result = HttpUnitl.sendPost("http://api.iwei100.com/request/tick/getTradeDate.html", "startDate="+day+"&endDate="+nextday+"");
				JSONObject json=JSONObject.parseObject(result);
				String days = String.valueOf(json.get("result"));	
				System.err.println(result);
				 synchronized(this){  
					 if("1".equals(days)){
						 boolean inTime = CommTools.isInTime("09:30", "11:30");
						 boolean inTime2 = CommTools.isInTime("13:00", "15:00");
						 if(inTime || inTime2){	
						
							List list = contractService.queryExpMonth();
							Date data = new Date();
							long times =data.getTime();
							List<String> strlist = new ArrayList<String>();
							for(int i=0;i<list.size();i++){
								String index=(String) list.get(i);
								String url = "http://yunhq.sse.com.cn:32041/v1/sho/list/tstyle/510050_"+index+"?callback=callback&select=contractid%2Clast%2Cchg_rate%2Cpresetpx%2Cexepx&_="+times;
								String str = DemoSelenium.httpURLConectionGET(url);
								System.err.println(str);
								strlist.add(str);
							}
							 contractService.addTadInfo(strlist);												
							
							String url1 = "http://yunhq.sse.com.cn:32041/v1/sh1/list/self/510050?callback=callback&select=code%2Cname%2Clast%2Cchange%2Cchg_rate%2Camp_rate%2Cvolume%2Camount%2Cprev_close&_="+times;
										
							String httpURL = DemoSelenium.httpURLConectionGET(url1);	
							System.err.println("httpURL="+httpURL);
							 contractService.addMarkInfo(httpURL);
						 	}
					 	}
					 }
						System.err.println("结束");					
						 
						Thread.sleep(times);
						
					} catch (Exception e) {					
						e.printStackTrace();						
						doBusiness();
		                break;
					}
				 
				}
	}
	
}
